import axios from 'axios'
import config from '../utils/config'
import {
  getTokenInfo
} from '../utils/publicFun'

const whiteList = config.ROTER_WHITE_LIST
// 创建axios实例
const baseUrl = config.BASE_URL
const requestTimeout = config.REQUEST_TIMEOUT
const service = axios.create({
  baseURL: baseUrl,
  timeout: requestTimeout // 请求超时时间
})
// 请求拦截拦截器
service.interceptors.request.use(
  config => {
    config.headers.userName = (() => {
      if (localStorage.userInfo) {
        return JSON.parse(localStorage.userInfo).userName
      } else {
        return ''
      }
    })()
    config.headers.userId = (() => {
      if (localStorage.userInfo) {
        return JSON.parse(localStorage.userInfo).userId
      } else {
        return ''
      }
    })()
    config.headers.realname = (() => {
      if (localStorage.userInfo) {
        return encodeURIComponent(JSON.parse(localStorage.userInfo).realname)
      } else {
        return ''
      }
    })()
    if (config.url !== '/sys-user/login' && config.url !== 'token/getToken') {
      config.headers.token = (() => {
        if (getTokenInfo()) {
          return getTokenInfo()
        } else {
          if (whiteList.indexOf(location.pathname) === -1) {
            // console.log('toLogin')
            location.href = '/login'
            localStorage.removeItem('userInfo')
          }
        }
      })()
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)
// 响应拦截
service.interceptors.response.use(
  res => {
    return res
  },
  // 请求失败情况
  error => {
    const {
      response
    } = error
    if (response) {
      // 若状态码为 510 或者 401， 跳转至登录界面
      if (response.status === 510 || response.status === 401 || response.status === 512) {
        console.log('排查-是否为网络问题')
        localStorage.userInfo = ''
        localStorage.tokenInfo = ''
        location.href = '/login'
      }
      return Promise.reject(response)
    } else {
      if (error.message) {
        console.log(error.message)
      } else {
        console.log('服务故障，请检查！')
      }
      return Promise.resolve()
    }
  })

export default service
